﻿@{
    ViewBag.Title = "数据树";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@section styles{
    <link href="~/lib/zTree_v3/css/zTreeStyle/zTreeStyle.css" rel="stylesheet" />
    <style>
        .layui-input {
            max-width: 70% !important;
        }
        /*删除上传图片按钮*/
        .btn_deleteImg {
            width: 20px;
            height: 20px;
            border-radius: 2px;
            cursor: pointer;
            position: absolute;
            right: 5px;
            top: 5px;
            z-index: 10;
            opacity: 0.6;
            background: url(../images/iconDelete.png) center center no-repeat #009688;
            background-size: auto 16px;
        }

            .btn_deleteImg:hover {
                opacity: 1;
            }

        .list-img {
            height: 120px;
            width: 170px;
            background: rgba(0, 0, 0, .1);
            /*float: left;*/
            font-size: 14px;
            text-align: center;
            color: #999;
            position: relative;
            overflow: hidden;
        }

            .list-img .layui-upload-img {
                transform-origin: left top 0px;
                will-change: transform;
                transform: translate(0px, 0px) scale(0.283333) rotate(0deg);
            }

        .layui-inline .layui-upload {
            text-align: center;
        }
        /*删除上传图片按钮-end*/
        .layui-body {
            display: flex;
            margin: 30px;
            border: 1px solid #e6e6e6;
        }
        .btnDiv {
            text-align: center;
            margin-top: 5px;
        }
    </style>
}


    <div class="layui-body " style="display:flex;margin:30px;border:1px solid #e6e6e6; ">

        <div style="margin:15px; width:230px;">
            <ul id="treeDemo" style="margin-bottom:10px;" class="ztree"></ul>
            <button class="layui-btn layui-inline layui-btn-sm" id="btnAdd" type="button">新增</button>
            <button class="layui-btn layui-inline layui-btn-sm" id="btnSubmitTest" type="button">立即提交</button>
            <button class="layui-btn layui-inline layui-btn-sm" id="btnDelete" type="button">删除</button>
        </div>
        <div style="width:100%;  overflow-y:scroll; height:100%;">
            <form class="layui-form layui-form-pane" id="baseTreeForm" action="" style=" margin-top:10px;border-left:1px solid #e6e6e6; padding-left:10px;" lay-filter="example">
                <div class="layui-tab">
                    <ul class="layui-tab-title">
                        <li class="layui-this">基本数据</li>
                        <li>扩展数据</li>

                    </ul>
                    <div class="layui-tab-content">
                        <div class="layui-tab-item layui-show">

                            <div class="layui-form-item">
                                <label class="layui-form-label">Id</label>
                                <div class="layui-inline">
                                    <input type="text" name="Id" id="Id" value="" autocomplete="off" placeholder="Id" readonly="readonly" class="layui-input" />
                                </div>
                                <div class="layui-inline">
                                    <span style="color:red">Id只读，用于开发者快速复制</span>
                                </div>

                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">树名称</label>
                                <div class="layui-input-block">
                                    <input type="text" name="TreeName" id="TreeName" style=" max-width: 50% !important;" lay-verify="required" autocomplete="off" placeholder="树名称" class="layui-input" />
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">父节点</label>
                                <div class="layui-input-block">
                                    <input type="text" name="PName" id="PName" onclick="showMenu();" readonly="readonly" style="max-width: 50% !important;" lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
                                    <div id="menuContent" class="menuContent" style="display:none; position: absolute;z-index:1000;border:1px solid red; background-color:white;width:auto;">
                                        <ul id="treeMenu" class="ztree" style="margin-top:0; min-width:230px;width:auto;"></ul>
                                    </div>
                                    <input type="hidden" name="PId" id="PId" value="" autocomplete="off">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">字段1</label>
                                <div class="layui-input-block">
                                    <input type="text" name="Extend1" id="Extend1" style="max-width: 50% !important;" placeholder="请输入" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">字段2</label>
                                <div class="layui-input-block">
                                    <input type="text" name="Extend2" id="Extend2" style="max-width: 50% !important;" placeholder="请输入" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">字段3</label>
                                <div class="layui-input-block">
                                    <input type="text" name="Extend3" id="Extend3" style="max-width: 50% !important;" placeholder="请输入" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">字段4</label>
                                <div class="layui-input-block">
                                    <input type="text" name="Extend4" id="Extend4" style="max-width: 50% !important;" placeholder="请输入" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">字段5</label>
                                <div class="layui-input-block">
                                    <input type="text" name="Extend5" id="Extend5" style="max-width: 25% !important;" placeholder="请输入" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">排序</label>
                                <div class="layui-input-block">
                                    <input type="number" style="max-width: 10% !important;" name="Sort" value="0" id="Sort" lay-verify="required"
                                           placeholder="请输入排序" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-form-item" pane="">
                                <label class="layui-form-label">是否显示</label>
                                <div class="layui-input-block">
                                    <input type="checkbox" name="State" id="State" lay-skin="switch" lay-filter="switchTest" lay-text="显示|隐藏" checked="checked" title="开关">
                                </div>
                            </div>
                            <div class="layui-form-item layui-form-text">
                                <label class="layui-form-label">字段6</label>
                                <div class="layui-input-block">
                                    <textarea placeholder="请输入内容" name="Extend6" id="Extend6" class="layui-textarea"></textarea>
                                </div>
                            </div>




                        </div>
                        <div class="layui-tab-item">

                            <div class="layui-form-item">
                                <div class="layui-inline">
                                    <label class="layui-form-label">开始时间</label>
                                    <div class="layui-input-inline" style="width:230px;">
                                        <input type="text" style="width:230px;" name="StartTime" id="StartTime" placeholder="yyyy-MM-dd" autocomplete="off" class="layui-input">
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label">结束时间</label>
                                    <div class="layui-input-inline" style="width:230px;">
                                        <input type="text" name="EndTime" style="width:230px;" id="EndTime" placeholder="yyyy-MM-dd" autocomplete="off" class="layui-input">
                                    </div>
                                </div>

                            </div>
                            <div class="layui-form-item">
                                <div class="layui-inline">
                                    <label class="layui-form-label" title="上传图片">上传图片</label>
                                </div>
                                <div class="layui-inline">

                                    <div class="layui-inline" style="vertical-align:top">
                                        <div class="layui-upload">
                                            <div class="layui-upload-list">
                                                <div class="list-img">
                                                    <img class="layui-upload-img" id="img01" name="img01" style="">
                                                    <div class="btn_deleteImg img01"></div>
                                                </div>
                                            </div>
                                            <p id="img01Text"></p>

                                            <button type="button" class="layui-btn" id="btImg01">上传图片</button>
                                            <input type="hidden" name="ImgUrl1" id="ImgUrl1" v-model="ImgUrl1" />
                                            <input type="hidden" name="ImageId01" id="ImageId01" v-model="ImageId01" />
                                        </div>
                                    </div>
                                    <div class="layui-inline" style="vertical-align:top">
                                        <div class="layui-upload">
                                            <div class="layui-upload-list">
                                                <div class="list-img">
                                                    <img class="layui-upload-img" id="img02" name="img02">
                                                    <div class="btn_deleteImg img02"></div>
                                                </div>
                                            </div>
                                            <p id="img02Text"></p>
                                            <button type="button" class="layui-btn" id="btImg02">上传图片</button>
                                            <input type="hidden" name="ImgUrl2" id="ImgUrl2" v-model="ImgUrl2" />
                                            <input type="hidden" name="ImageId02" id="ImageId02" model="ImageId02" />
                                        </div>
                                    </div>
                                    <div class="layui-inline" style="vertical-align:top">
                                        <div class="layui-upload">
                                            <div class="layui-upload-list">
                                                <div class="list-img">
                                                    <img class="layui-upload-img" id="img03" name="img03">
                                                    <div class="btn_deleteImg img03"></div>
                                                </div>
                                            </div>
                                            <p id="img03Text"></p>
                                            <button type="button" class="layui-btn" id="btImg03">上传图片</button>
                                            <input type="hidden" name="ImgUrl3" id="ImgUrl3" v-model="ImgUrl3" />
                                            <input type="hidden" name="ImageId03" id="ImageId03" model="ImageId03" />
                                        </div>
                                    </div>
                                </div>
                            </div>

                            @*<div class="layui-form-item" pane="">
                                <label class="layui-form-label">是否删除</label>
                                <div class="layui-input-block">
                                    <input type="checkbox" name="IsDelete" id="IsDelete" lay-skin="switch" lay-text="删除|正常" lay-filter="switchTest" title="开关">
                                </div>
                            </div>*@
                            <div class="layui-form-item layui-form-text">
                                <label class="layui-form-label">富文本</label>
                                <div class="layui-input-block" id="remarkcontent">
                                    <script id="editor" name="Context" v-model="Context" type="text/plain" style="height:500px;width:900px;">
                                    </script>
                                    @*<textarea placeholder="请输入内容" id="Context" name="Context" class="layui-textarea"></textarea>*@
                                </div>
                            </div>

                        </div>
                    </div>
                </div>
                <div class="layui-form-item" style="padding-top:20px">
                    <div class="layui-input-block">
                        <button class="layui-btn" id="btnSubmit" type="button" lay-submit="" lay-filter="demo1">立即提交</button>
                        @*<button class="layui-btn layui-btn-submit" lay-submit lay-filter="formSubmit">立即提交</button>*@

                    </div>
                </div>
            </form>
        </div>


    </div>




@section scripts{
    <script src="~/lib/zTree_v3/js/jquery.ztree.core.js"></script>
    <script src="~/js/Common.js"></script>
    <SCRIPT type="text/javascript">


        function onClick(e, treeId, treeNode) {
            var form = layui.form;
            //表单初始赋值
            form.val('example', {
                "PId": treeNode.id,
                "PName": treeNode.name
            })
            layui.form.render();
            hideMenu();
        }

        function showMenu() {
            var cityObj = $("#PName");
            var cityOffset = $("#PName").offset();
            //.css({ left: cityOffset.left + "px", top: cityOffset.top + cityObj.outerHeight() + "px" })
            $("#menuContent").slideDown("fast");

            $("body").bind("mousedown", onBodyDown);
        }
        function hideMenu() {
            $("#menuContent").fadeOut("fast");
            $("body").unbind("mousedown", onBodyDown);
        }
        function onBodyDown(event) {
            if (!(event.target.id == "menuBtn" || event.target.id == "menuContent" || $(event.target).parents("#menuContent").length > 0)) {
                hideMenu();
            }
        }

        //{
        //    async: {
        //        enable: true,
        //            url: window.UrlBase + "Basetree/QueryTreeByPid",
        //                autoParam: ["id", "name=n", "level=lv"],
        //                    otherParam: { "otherParam": "zTreeAsyncTest" },
        //        dataFilter: filter
        //    },
        //    callback: {
        //        onClick: zTreeOnClick
        //    }
        var settingmenu = {
            view: {
                dblClickExpand: false
            },
            data: {
                simpleData: {
                    enable: true
                }
            },
            async: {
                enable: true,
                url: window.UrlBase + "Basetree/QueryTreeByPid",
                autoParam: ["id", "name=n", "level=lv"],
                otherParam: { "flag": "1" },
                dataFilter: filter
            },
            callback: {
                onClick: onClick
            }
        };




        var setting = {
            async: {
                enable: true,
                url: window.UrlBase + "Basetree/QueryTreeByPid",
                autoParam: ["id", "name=n", "level=lv"],
                otherParam: { "otherParam": "zTreeAsyncTest" },
                dataFilter: filter
            },
            callback: {
                onClick: zTreeOnClick
            },
            view: {
                addDiyDom: addDiyDom
            }

        };

        function addDiyDom(treeId, treeNode) {
            var spaceWidth = 5;
            var switchObj = $("#" + treeNode.tId + "_switch"),
                icoObj = $("#" + treeNode.tId + "_ico");
            switchObj.remove();
            icoObj.parent().before(switchObj);
            var spantxt = $("#" + treeNode.tId + "_span").html();
            if (spantxt.length > 13) {
                spantxt = spantxt.substring(0, 13) + "...";
                $("#" + treeNode.tId + "_span").html(spantxt);
            }
        }

        function refreshParentNode(PId, treeId) {
            console.log("PId:" + PId + ",treeId=" + treeId);
            var treeObj = $.fn.zTree.getZTreeObj(treeId);
            var node = treeObj.getNodesByParam("id", PId, null);

            if (PId == 0) {
                treeObj.reAsyncChildNodes(null, "refresh");
            }
            else {
                node[0].isParent = true;
                console.log(node[0]);
                treeObj.reAsyncChildNodes(node[0], "refresh");
            }

        }

        function reset() {
            $('#baseTreeForm')[0].reset();
            $("#img01").attr('src', '');
            $("#img02").attr('src', '');
            $("#img03").attr('src', '');
            layui.form.render();
        }
        function zTreeOnClick(event, treeId, childNodes) {
            console.log(treeId);
            //console.log(childNodes.id + '--' + encodeURI(childNodes.name));
            if (childNodes.id == 0) {
                reset();
            }
            else {
                GetTreeInfo(childNodes.id);
            }
            //parent.article_main.location.href = "NewsQuery.aspx?id=" + childNodes.id + "&name=" + encodeURI(childNodes.name);

        };
        function filter(treeId, parentNode, childNodes) {
            if (!childNodes) return null;

            for (var i = 0, l = childNodes.length; i < l; i++) {
                childNodes[i].name = childNodes[i].name.replace(/\.n/g, '.');
            }
            return childNodes;
        }

        $(document).ready(function () {
            $.fn.zTree.init($("#treeDemo"), setting);
            $.fn.zTree.init($("#treeMenu"), settingmenu);
            $("#btnAdd").click(function () {
                reset();
            })
            $("#btnSubmitTest").click(function () {
                $("#btnSubmit").click();
            })
            UE.delEditor('editor');
            //实例化编辑器
            //建议使用工厂方法getEditor创建和引用编辑器实例，如果在某个闭包下引用该编辑器，直接调用UE.getEditor('editor')就能拿到相关的实例
            var ue = UE.getEditor('editor');
            ue.addListener('ready', function (editor) { //编辑器加载完成后
                //if (data.Remark) {
                //    ue.setContent(data.Remark, false);
                //} else {
                //    ue.setContent("", false);
                //}
            });
            $("#remarkcontent").html(document.getElementById("editor"));
        });
        var OldData;
        function GetTreeInfo(Id) {
            $.post(window.UrlBase + 'Basetree/GetTreeInfo', { Id: Id }, function (result) {
                if (result.Status == 1) {
                    OldData = result.Data;
                    var form = layui.form;
                    //表单初始赋值
                    form.val('example', {
                        "Id": result.Data.Id,
                        "PId": result.Data.PId,
                        "PName": result.Data.PName,
                        "TreeName": result.Data.TreeName,
                        "Extend1": result.Data.Extend1,
                        "Extend2": result.Data.Extend2,
                        "Extend3": result.Data.Extend3,
                        "Extend4": result.Data.Extend4,
                        "Extend5": result.Data.Extend5,
                        "Extend6": result.Data.Extend6,
                        "Sort": result.Data.Sort,
                        "StartTime": formatDate(result.Data.StartTime),
                        "EndTime": formatDate(result.Data.EndTime),
                        "ImgUrl1": result.Data.ImgUrl1,
                        "ImgUrl2": result.Data.ImgUrl2,
                        "ImgUrl3": result.Data.ImgUrl3,
                        "State": result.Data.State, // "name": "value"
                        "IsDelete": result.Data.IsDelete // "name": "value"
                    })
                    //实例化编辑器
                    //建议使用工厂方法getEditor创建和引用编辑器实例，如果在某个闭包下引用该编辑器，直接调用UE.getEditor('editor')就能拿到相关的实例
                    var ue = UE.getEditor('editor');
                    ue.setContent(result.Data.Context);

                    $("#img01").attr('src', result.Data.ImgUrl1);
                    $("#img02").attr('src', result.Data.ImgUrl2);
                    $("#img03").attr('src', result.Data.ImgUrl3);
                    layui.form.render();
                }

            }, "json")
        }
    </SCRIPT>

    <script>
        //$(".BaseTreeMain").addClass("layui-this");
        var menu = $(".BaseTreeMain");
        menu.addClass("layui-this ");
        if (menu[0].tagName == 'DD') {
            menu.parent().parent().addClass("layui-nav-itemed");
        }
    </script>
    <script>

        layui.use(['form', 'jquery', 'table'], function () {
            //layui变量
            var
                table = layui.table,
                form = layui.form,
                $ = layui.jquery,
                upload = layui.upload,
                laydate = layui.laydate;


            $("#btnDelete").click(function () {
                if ($("#Id").val() == "") {
                    layer.alert("请选择要删除的树菜单", {
                        title: '提示'
                    })
                    return;
                }
                layer.confirm('您确认要删除当前记录？', { btn: ['确定', '取消'], title: "提示" },
                    function (index) {
                        var loading = layer.load(1, {
                            shade: [0.3, '#fff'] //0.1透明度的白色背景
                        });
                        console.log($("#Id").val());
                        layer.close(index);
                        $.post(window.UrlBase + 'BaseTree/Delete', { id: $("#Id").val() }, function (data) {
                            layer.close(loading);
                            if (data.Status == 1) {
                                layer.alert("删除成功", {
                                    title: '提示'
                                })
                                reset();
                                var PId = $("#PId").val();
                                refreshParentNode(PId, "treeDemo");
                                refreshParentNode(PId, "treeMenu");
                            }
                            else {
                                layer.alert("删除失败", {
                                    title: '提示'
                                })
                            }

                        }, "json")

                    });
            });
            //日期
            laydate.render({
                elem: '#StartTime'
                , type: 'datetime'
                , format: 'yyyy-MM-dd HH:mm:ss',
            });
            laydate.render({
                elem: '#EndTime'
                , type: 'datetime'
                , format: 'yyyy-MM-dd HH:mm:ss',
            });


            //监听提交
            form.on('submit(demo1)', function (data) {

                if (data.field.TreeName.length > 50) {
                    layer.alert("树名称不能超过50个字符", {
                        title: '提交失败'
                    });
                    return false;
                }

                //loading层
                var loading = layer.load(1, {
                    shade: [0.3, '#fff'] //0.1透明度的白色背景
                });

                data.field.State = data.field.State == "on" ? true : false;
                data.field.IsDelete = data.field.IsDelete == "on" ? true : false;
                var ue = UE.getEditor('editor');
                data.field.Context = ue.getContent();
                //layer.alert(JSON.stringify(data.field), {
                //    title: '最终的提交信息'
                //})
                $.post(window.UrlBase + 'Basetree/Edit', data.field, function (result) {

                    layer.close(loading);
                    if (result.Status == 1) {
                        refreshParentNode(data.field.PId, "treeDemo");
                        refreshParentNode(data.field.PId, "treeMenu");
                        if (data.field.PId != OldData.PId) {
                            refreshParentNode(OldData.PId, "treeDemo");
                            refreshParentNode(OldData.PId, "treeMenu");
                        }

                        layer.alert("提交成功", {
                            title: '提示'
                        })
                    }
                    else {
                        layer.alert(result.Message, {
                            title: '提交失败'
                        })
                    }
                }, "json");
                return false;
            });





            //图片上传
            var uploadInst01 = upload.render({
                elem: '#btImg01'
                , url: UrlBase + 'Upload/Upload'
                , data: { t: 0 }
                , accept: 'images' //指定允许上传时校验的文件类型，可选值有：images（图片）、file（所有文件）、video（视频）、audio（音频）
                , exts: "jpg|png|gif|bmp|jpeg|svg"
                , multiple: false  //是否允许多文件上传
                , number: 1 // 设置同时可上传的文件数量，一般配合 multiple 参数出现。
                , drag: true  //是否接受拖拽的文件上传，设置 false 可禁用。不支持ie8/9
                , before: function (obj) {
                    //预读本地文件示例，不支持ie8
                    obj.preview(function (index, file, result) {
                        $('#img01').attr('src', result); //图片链接（base64）
                    });
                }
                , done: function (res) {
                    // console.log(res);
                    //如果上传失败
                    if (res.Status < 1) {
                        $('#ImgUrl1').val("");
                        $('#ImageId01').val("");
                        return layer.msg(res.Message);
                    } else {
                        $('#ImgUrl1').val(res.Data.FileUrl);
                        $('#ImageId01').val(res.FileName);
                    }

                    //上传成功
                }
                , error: function () {
                    //演示失败状态，并实现重传
                    var demoText = $('#img01Text');
                    demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs img01-reload">重试</a>');
                    demoText.find('.img01-reload').on('click', function () {
                        uploadInst01.upload();
                    });
                }
            });

            var uploadInst02 = upload.render({
                elem: '#btImg02'
                , url: UrlBase + 'Upload/Upload'
                , data: { t: 0 }
                , accept: 'images' //指定允许上传时校验的文件类型，可选值有：images（图片）、file（所有文件）、video（视频）、audio（音频）
                , exts: "jpg|png|gif|bmp|jpeg|svg"
                , multiple: false  //是否允许多文件上传
                , number: 1 // 设置同时可上传的文件数量，一般配合 multiple 参数出现。
                , drag: true  //是否接受拖拽的文件上传，设置 false 可禁用。不支持ie8/9
                , before: function (obj) {
                    //预读本地文件示例，不支持ie8
                    obj.preview(function (index, file, result) {
                        $('#img02').attr('src', result); //图片链接（base64）
                    });
                }
                , done: function (res) {
                    // console.log(res);
                    //如果上传失败
                    if (res.Status < 1) {
                        $('#ImgUrl2').val("");
                        $('#ImageId02').val("");
                        return layer.msg(res.Message);
                    } else {
                        $('#ImgUrl2').val(res.Data.FileUrl);
                        $('#ImageId02').val(res.FileName);
                    }
                }
                , error: function () {
                    //演示失败状态，并实现重传
                    var demoText = $('#img02Text');
                    demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs img02-reload">重试</a>');
                    demoText.find('.img02-reload').on('click', function () {
                        uploadInst02.upload();
                    });
                }
            });

            var uploadInst03 = upload.render({
                elem: '#btImg03'
                , url: UrlBase + 'Upload/Upload'
                , data: { t: 0 }
                , accept: 'images' //指定允许上传时校验的文件类型，可选值有：images（图片）、file（所有文件）、video（视频）、audio（音频）
                , exts: "jpg|png|gif|bmp|jpeg|svg"
                , multiple: false  //是否允许多文件上传
                , number: 1 // 设置同时可上传的文件数量，一般配合 multiple 参数出现。
                , drag: true  //是否接受拖拽的文件上传，设置 false 可禁用。不支持ie8/9
                , before: function (obj) {
                    //预读本地文件示例，不支持ie8
                    obj.preview(function (index, file, result) {
                        $('#img03').attr('src', result); //图片链接（base64）
                    });
                }
                , done: function (res) {
                    // console.log(res);
                    //如果上传失败
                    if (res.Status < 1) {
                        $('#ImgUrl3').val("");
                        $('#ImageId03').val("");
                        return layer.msg(res.Message);
                    } else {
                        $('#ImgUrl3').val(res.Data.FileUrl);
                        $('#ImageId03').val(res.FileName);
                    }
                }
                , error: function () {
                    //演示失败状态，并实现重传
                    var demoText = $('#img03Text');
                    demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs img03-reload">重试</a>');
                    demoText.find('.img03-reload').on('click', function () {
                        uploadInst03.upload();
                    });
                }
            });

        });



    </script>
}